package com.spzx.channel.configure;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 * projectName: spzx-parent
 *
 * @author: 王宝贵
 * time: 2024/10/12 15:09 周六
 * description:
 */
@Configuration
public class ThreadPoolConfig {


    @Bean
    public ThreadPoolExecutor threadPoolExecutor(){
        //当前电脑的cpu数量
        int threads = Runtime.getRuntime().availableProcessors();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                threads + 1,
                threads * 2,
                0,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(200),
                Executors.defaultThreadFactory(), //创建线程池工厂
                //new ThreadPoolExecutor.CallerRunsPolicy()
                new  RejectedExecutionHandler(){

                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //将拒绝的任务提交线程池执行
                        executor.submit(r);
                    }
                });


        //线程池创建 核心线程同时创建
       // threadPoolExecutor.prestartCoreThread();
        threadPoolExecutor.prestartAllCoreThreads();

        return threadPoolExecutor;

    }
}